using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.IO.Ports;

using SerialPortIO;

namespace SerialPortReader
{
    public partial class MainForm : Form
    {
        private PortHandler portHandler;
        
        public MainForm()
        {
            InitializeComponent();

            portHandler = new PortHandler(new SerialPort());
        }

        private void initLookups()
        {
            string[] ports = SerialPort.GetPortNames();
            if (ports.Length == 0)
            {
                MessageBox.Show("No ports found.");
                Application.Exit();
            }
            cbPort.DataSource = ports;
            cbParity.DataSource = Enum.GetValues(typeof(Parity));
            cbStopBits.DataSource = Enum.GetValues(typeof(StopBits));
            cbHandshake.DataSource = Enum.GetValues(typeof(Handshake));
        }

        private void setBindings()
        {
            cbPort.DataBindings.Add(new Binding("SelectedItem", portHandler, "PortName"));
            numUDBaudRate.DataBindings.Add(new Binding("Value", portHandler, "BaudRate"));
            cbParity.DataBindings.Add(new Binding("SelectedItem", portHandler, "Parity"));
            numUDDataBits.DataBindings.Add(new Binding("Value", portHandler, "DataBits"));
            cbStopBits.DataBindings.Add(new Binding("SelectedItem", portHandler, "StopBits"));
            cbHandshake.DataBindings.Add(new Binding("SelectedItem", portHandler, "Handshake"));
        }

        private void writeLog(string filename)
        {
            using (StreamWriter sw = File.AppendText(filename))
            {
                sw.Write(portHandler.ReadBuffer);
                sw.Flush();
                sw.Close();
            }
        }


        #region EVENTS

        private void OnLoad(object sender, EventArgs e)
        {
            initLookups();
            setBindings();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            portHandler.StartReading(tbStartString.Text, new ExampleDataHandler());
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            portHandler.Stop();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveLogFileDialog = new SaveFileDialog();
            saveLogFileDialog.InitialDirectory = "c:\\";
            saveLogFileDialog.Filter = "log files (*.log)|*.log";
            saveLogFileDialog.FilterIndex = 1;
            saveLogFileDialog.RestoreDirectory = true;
            if (saveLogFileDialog.ShowDialog() == DialogResult.OK)
                writeLog(saveLogFileDialog.FileName);
        }

        #endregion




        

        

        

    }
}